import React, {Component} from 'react';

class Count extends Component {


  state = {
    count: 0, // 当前的求和的值
  }

  increment = () => {
    // 点击加执行的事件
    const {value} = this.selectedNumber;
    const {count} = this.state;
    this.setState({count: count + value * 1})
  }

  decrement = () => {
    // 点击减触发的事件
    const {value} = this.selectedNumber;
    const {count} = this.state;
    this.setState({count: count - value * 1});
  }

  incrementIfOdd = () => {
    // 当前和为奇数时再加
    const {count} = this.state;
    if (count % 2 !== 0) {
      const {value} = this.selectedNumber;
      this.setState({count: count + value * 1})
    }
  }

  timeOutMethod = (fn, wait = 500) => {
    let timeout;
    return function (event) {
      clearTimeout(timeout);  // 每次触发时先清除上一次的定时器,然后重新计时
      timeout = setTimeout(() => {
        fn(event)
      }, wait);
    }
  }


  incrementIfAsync = () => {
    // 异步加法
    const {value} = this.selectedNumber;
    const {count} = this.state;
    this.timeOutMethod(() => {
      this.setState({count: count + value * 1})
    })();
  }

  render() {
    const {count} = this.state;
    return (
      <div>
        <h1>当前求和为{count}</h1>
        <select ref={c => this.selectedNumber = c}>
          <option value="1">1</option>
          <option value="2">2</option>
          <option value="3">3</option>
        </select>
        &nbsp;
        <button onClick={this.increment}>加</button>
        &nbsp;
        <button onClick={this.decrement}>减</button>
        &nbsp;
        <button onClick={this.incrementIfOdd}>当前求和为奇数再加</button>
        &nbsp;
        <button onClick={this.incrementIfAsync}>异步加</button>
      </div>
    );
  }
}

export default Count;